package cn.wolfcode.car.business.service.impl;

import cn.wolfcode.car.business.domain.BpmnInfo;
import cn.wolfcode.car.business.mapper.BpmnInfoMapper;
import cn.wolfcode.car.business.query.BpmnInfoQuery;
import cn.wolfcode.car.business.service.IBpmnInfoService;
import cn.wolfcode.car.common.base.page.TablePageInfo;
import cn.wolfcode.car.common.config.SystemConfig;
import cn.wolfcode.car.common.exception.BusinessException;
import cn.wolfcode.car.common.util.Convert;
import cn.wolfcode.car.common.util.file.FileUploadUtils;
import cn.wolfcode.car.common.util.file.FileUtils;
import com.github.pagehelper.PageHelper;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.image.impl.DefaultProcessDiagramGenerator;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.Collections;
import java.util.List;
import java.util.zip.ZipInputStream;

@Service
@Transactional
public class BpmnInfoServiceImpl implements IBpmnInfoService {

    @Autowired
    private BpmnInfoMapper bpmnInfoMapper;
    @Autowired
    private RepositoryService repositoryService;


    @Override
    public TablePageInfo<BpmnInfo> query(BpmnInfoQuery qo) {
        PageHelper.startPage(qo.getPageNum(), qo.getPageSize());
        return new TablePageInfo<BpmnInfo>(bpmnInfoMapper.selectForList(qo));
    }


    @Override
    public void save(BpmnInfo bpmnInfo) {
        bpmnInfoMapper.insert(bpmnInfo);
    }

    @Override
    public BpmnInfo get(Long id) {
        return bpmnInfoMapper.selectByPrimaryKey(id);
    }


    @Override
    public void update(BpmnInfo bpmnInfo) {
        bpmnInfoMapper.updateByPrimaryKey(bpmnInfo);
    }

    @Override
    public void deleteBatch(String ids) {
        Long[] dictIds = Convert.toLongArray(ids);
        for (Long dictId : dictIds) {
            bpmnInfoMapper.deleteByPrimaryKey(dictId);
        }
    }

    @Override
    public List<BpmnInfo> list() {
        return bpmnInfoMapper.selectAll();
    }

    @Override
    public void updateInfo(BpmnInfo bpmnInfo) {
        bpmnInfoMapper.updateInfo(bpmnInfo);
    }

    @Override
    public String upload(MultipartFile file) {
        if (file != null && file.getSize() > 0) {
            String filename = file.getOriginalFilename();
            String exp = FilenameUtils.getExtension(filename);
            String path = null;
            if("zip".equalsIgnoreCase(exp) || "bpmn".equalsIgnoreCase(exp)){
                try {
                    path = FileUploadUtils.upload(SystemConfig.getUploadPath(), file);
                    return path;
                } catch (IOException e) {
                    e.printStackTrace();
                    throw new BusinessException("流程文件上传失败!");
                }
            }else {
                throw new BusinessException("流程定义文件仅支持 bpmn 和 zip 格式！");
            }
        }else{
            throw new BusinessException("不允许上传空文件！");
        }
    }

    @Override
    public void deploy(String bpmnPath, String bpmnType, String info) throws FileNotFoundException {
        // 部署流程定义
        String path = bpmnPath.toLowerCase();
        InputStream stream = new FileInputStream(new File(SystemConfig.getProfile(), bpmnPath));
        Deployment deploy = null;
        if(path.endsWith("zip")){
             deploy = repositoryService.createDeployment()
                    .addZipInputStream(new ZipInputStream(stream))
                    .deploy();
        }else if(path.endsWith("bpmn")){
            deploy = repositoryService.createDeployment()
                    .addInputStream(bpmnPath,stream)
                    .deploy();
        }
        if (deploy == null) {
            throw new BusinessException("部署失败!");
        }
        BpmnInfo bpmnInfo = new BpmnInfo();
        bpmnInfo.setInfo(info);
        bpmnInfo.setBpmnPath(bpmnPath);
        bpmnInfo.setBpmnType(bpmnType);
        bpmnInfo.setDeploymentId(deploy.getId());
        bpmnInfo.setDeployTime(deploy.getDeploymentTime());

        ProcessDefinition definition = repositoryService.createProcessDefinitionQuery()
                .deploymentId(deploy.getId())
                .latestVersion()
                .singleResult();
        bpmnInfo.setBpmnName(definition.getName());
        bpmnInfo.setActProcessId(definition.getId());
        bpmnInfo.setActProcessKey(definition.getKey());

        bpmnInfoMapper.insert(bpmnInfo);
    }

    @Override
    public void delete(Long id) {
        BpmnInfo bpmnInfo = bpmnInfoMapper.selectByPrimaryKey(id);
        // 删除流程部署对象记录,流程定义数据
        repositoryService.deleteDeployment(bpmnInfo.getDeploymentId(), true);
        // 流程文件
        File file = new File(SystemConfig.getProfile(), bpmnInfo.getBpmnPath());

        if(file.exists()){
            file.delete();
        }
        // 删除审核流程定义对象
        bpmnInfoMapper.deleteByPrimaryKey(id);
    }

    @Override
    public InputStream readResource(String deploymentId, String type) {
        ProcessDefinition definition = repositoryService.createProcessDefinitionQuery()
                .deploymentId(deploymentId)
                .latestVersion()
                .singleResult();
        if("xml".equalsIgnoreCase(type)){
            return repositoryService.getResourceAsStream(deploymentId,definition.getResourceName());
        }else if ("png".equalsIgnoreCase(type)){
            BpmnModel model = repositoryService.getBpmnModel(definition.getId());
            DefaultProcessDiagramGenerator generator = new DefaultProcessDiagramGenerator();
            return generator.generateDiagram(model, Collections.EMPTY_LIST,Collections.EMPTY_LIST,"宋体","宋体","宋体");
        }
        return null;
    }

    @Override
    public BpmnInfo queryByType(String type) {
        return bpmnInfoMapper.queryByType(type);
    }
}
